'use client'

import { useEffect, useState, useMemo, useCallback , useRef } from 'react'
import { VmsTopic, VmsCopy } from '@/types/Model'
import { useRouter, useSearchParams } from 'next/navigation'
import { Button } from '@/components/ui/button'
import { DragDropContext, Droppable, Draggable, DroppableProvided, DroppableStateSnapshot } from '@hello-pangea/dnd'
import { toast } from '@/hooks/use-toast'
import { Search, FolderOpen, Clock, CheckCircle, Edit3, Video, Camera, GripVertical, Plus, Filter, ChevronDown, X } from 'lucide-react'

// 防抖 Hook
function useDebounce<T>(value: T, delay: number): T {
  const [debouncedValue, setDebouncedValue] = useState<T>(value)

  useEffect(() => {
    const handler = setTimeout(() => {
      setDebouncedValue(value)
    }, delay)

    return () => {
      clearTimeout(handler)
    }
  }, [value, delay])

  return debouncedValue
}

export default function ProgressPage() {
  const [topics, setTopics] = useState<VmsTopic[]>([])
  const [selectedTopic, setSelectedTopic] = useState<string>('')
  const [copies, setCopies] = useState<VmsCopy[]>([])
  const [loading, setLoading] = useState(true)
  const [searchTerm, setSearchTerm] = useState('')
  const [isDropdownOpen, setIsDropdownOpen] = useState(false)
  const [isComposing, setIsComposing] = useState(false)
  
  // 添加输入框和下拉框引用
  const searchInputRef = useRef<HTMLInputElement>(null)
  const dropdownRef = useRef<HTMLDivElement>(null)
  const router = useRouter()

  // 修改防抖逻辑，在输入法组合时不触发
  const debouncedSearchTerm = useDebounce(isComposing ? '' : searchTerm, 200)

  // 点击外部关闭下拉框
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setIsDropdownOpen(false)
      }
    }

    document.addEventListener('mousedown', handleClickOutside)
    return () => {
      document.removeEventListener('mousedown', handleClickOutside)
    }
  }, [])

  const fetchTopics = async () => {
    try {
      const token = localStorage.getItem('token')
      const response = await fetch('/api/topic', {
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        }
      })
      
      if (!response.ok) {
        if (response.status === 401) {
          router.push('/login')
          toast({
            title: '登录信息过期',
            description: '请重新登录',
            variant: 'destructive'
          })
          localStorage.clear()
          return
        }
      }
      
      const data = await response.json()
      setTopics(data)

      const params = new URLSearchParams(window.location.search)
      const topicId = params.get('topicid')
      if (topicId) {
        const topicExists = data.some((t: VmsTopic) => t.id === topicId)
        if (topicExists) {
          setSelectedTopic(topicId)
          return
        }
      }

      if (data.length > 0) {
        setSelectedTopic(data[0].id)
      } else {
        setSelectedTopic('')
        setLoading(false)
      }
    } catch (error) {
      console.error('Error fetching topics:', error)
      toast({
        title: '数据获取失败',
        description: error instanceof Error ? error.message : '未知错误',
        variant: 'destructive'
      })
    }
  }

  const fetchCopies = async (topicId: string) => {
    try {
      if (!topicId) return
      
      const token = localStorage.getItem('token')
      const response = await fetch(`/api/copy?topic_id=${topicId}`, {
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        }
      })
      
      if (!response.ok) throw new Error('Failed to fetch copies')
      
      const data = await response.json()
      setCopies(data)
    } catch (error) {
      console.error('Error fetching copies:', error)
      toast({
        title: '数据获取失败',
        description: error instanceof Error ? error.message : '未知错误',
        variant: 'destructive'
      })
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    fetchTopics()
  }, [])

  useEffect(() => {
    if (selectedTopic) {
      fetchCopies(selectedTopic)
    } else {
      setCopies([])
    }
  }, [selectedTopic])

  const handleDragEnd = async (result: any) => {
    if (!result.destination) return
    
    const originalCopies = [...copies]
    
    const updatedCopies = copies.map(copy => {
      if (copy.id === result.draggableId) {
        return {
          ...copy,
          status: result.destination.droppableId
        }
      }
      return copy
    })

    setCopies(updatedCopies)

    try {
      const token = localStorage.getItem('token')
      const response = await fetch('/api/copy/batch', {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify(updatedCopies)
      })

      if (!response.ok) {
        throw new Error('Failed to update order')
      }
      toast({
        title: '更新成功',
        description: '文案状态和顺序已更新',
      })
    } catch (error) {
      console.error('Error updating order:', error)
      setCopies(originalCopies)
      toast({
        title: '排序更新失败',
        description: error instanceof Error ? error.message : '未知错误',
        variant: 'destructive'
      })
    }
  }

  // 过滤项目列表
  const filteredTopics = useMemo(() => {
    if (!debouncedSearchTerm.trim()) {
      return topics
    }
    
    const searchLower = debouncedSearchTerm.toLowerCase().trim()
    return topics.filter(topic => 
      topic.name?.toLowerCase().includes(searchLower) || false
    )
  }, [topics, debouncedSearchTerm])

  // 获取当前选中的项目名称
  const selectedTopicName = useMemo(() => {
    const topic = topics.find(t => t.id === selectedTopic)
    return topic?.name || ''
  }, [topics, selectedTopic])

  // 搜索输入处理
  const handleSearchChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value
    setSearchTerm(value)
    setIsDropdownOpen(true)
  }, [])

  // 输入法事件处理
  const handleCompositionStart = useCallback(() => {
    setIsComposing(true)
  }, [])

  const handleCompositionEnd = useCallback((e: React.CompositionEvent<HTMLInputElement>) => {
    setIsComposing(false)
    setSearchTerm(e.currentTarget.value)
    setIsDropdownOpen(true)
  }, [])

  // 清空搜索
  const clearSearch = useCallback(() => {
    setSearchTerm('')
    setIsDropdownOpen(false)
    searchInputRef.current?.focus()
  }, [])

  // 选择项目
  const handleSelectTopic = useCallback((topicId: string) => {
    setSelectedTopic(topicId)
    setSearchTerm('')
    setIsDropdownOpen(false)
  }, [])

  // 打开/关闭下拉框
  const toggleDropdown = useCallback(() => {
    setIsDropdownOpen(!isDropdownOpen)
    if (!isDropdownOpen) {
      searchInputRef.current?.focus()
    }
  }, [isDropdownOpen])

  // 处理输入框焦点
  const handleInputFocus = useCallback(() => {
    setIsDropdownOpen(true)
  }, [])

  // 简化的状态配置 - 统一使用蓝色系
  const statusConfig = {
    '文案编辑中': {
      icon: Edit3,
      color: 'bg-blue-500',
      bgColor: 'bg-blue-50/50 dark:bg-blue-950/20',
      borderColor: 'border-blue-100 dark:border-blue-900/30',
      textColor: 'text-blue-700 dark:text-blue-300'
    },
    '脚本制作中': {
      icon: Video,
      color: 'bg-purple-500',
      bgColor: 'bg-purple-50/50 dark:bg-purple-950/20',
      borderColor: 'border-purple-100 dark:border-purple-900/30',
      textColor: 'text-purple-700 dark:text-purple-300'
    },
    '拍摄中': {
      icon: Camera, 
      color: 'bg-amber-500',
      bgColor: 'bg-amber-50/50 dark:bg-amber-950/20',
      borderColor: 'border-amber-100 dark:border-amber-900/30',
      textColor: 'text-amber-700 dark:text-amber-300'
    },
    '已完成': {
      icon: CheckCircle,
      color: 'bg-emerald-500',
      bgColor: 'bg-emerald-50/50 dark:bg-emerald-950/20', 
      borderColor: 'border-emerald-100 dark:border-emerald-900/30',
      textColor: 'text-emerald-700 dark:text-emerald-300'
    }
  }

  return (
    <div className="min-h-screen ">
      <div className="container mx-auto py-8 px-6">
        {/* 页面标题 */}
        <div className="mb-6">
          <div className="flex items-center gap-3 mb-2">
            <h1 className="text-3xl font-bold bg-gradient-to-r from-gray-900 to-gray-600 dark:from-gray-100 dark:to-gray-400 bg-clip-text text-transparent">
              项目进度管理
            </h1>
          </div>
          <p className="text-gray-600 dark:text-gray-400">跟踪和管理项目文案的制作进度</p>
        </div>

        {/* 自定义项目选择器 */}
        <div className="flex items-center gap-4 mb-6">
          <label className="text-sm font-medium text-gray-700 dark:text-gray-300 whitespace-nowrap">
            选择项目:
          </label>
          <div className="flex-1 max-w-md relative" ref={dropdownRef}>
            {/* 主输入框 */}
            <div className="relative">
              <div className="flex items-center w-full h-[40px] px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 focus-within:ring-2 focus-within:ring-rose-500 focus-within:border-transparent">
                <Search className="w-4 h-4 text-gray-400 flex-shrink-0 mr-2" />
                <input
                  ref={searchInputRef}
                  type="text"
                  placeholder={selectedTopicName || "搜索或选择项目..."}
                  value={searchTerm}
                  onChange={handleSearchChange}
                  onCompositionStart={handleCompositionStart}
                  onCompositionEnd={handleCompositionEnd}
                  onFocus={handleInputFocus}
                  className="flex-1 bg-transparent border-none outline-none text-sm text-gray-900 dark:text-gray-100 placeholder-gray-500 dark:placeholder-gray-400"
                  autoComplete="off"
                />
                {searchTerm && (
                  <button
                    type="button"
                    onClick={clearSearch}
                    className="ml-2 p-1 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors"
                  >
                    <X className="w-3 h-3" />
                  </button>
                )}
                <button
                  type="button"
                  onClick={toggleDropdown}
                  className="ml-2 p-1 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors"
                >
                  <ChevronDown className={`w-4 h-4 transition-transform duration-200 ${isDropdownOpen ? 'rotate-180' : ''}`} />
                </button>
              </div>
            </div>

            {/* 下拉列表 */}
            {isDropdownOpen && (
              <div className="absolute top-full left-0 right-0 mt-1 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg z-50 max-h-60 overflow-hidden">
                {/* 项目列表 */}
                <div className="max-h-60 overflow-y-auto">
                  {filteredTopics.length > 0 ? (
                    filteredTopics.map(topic => (
                      <div
                        key={topic.id}
                        onClick={() => handleSelectTopic(topic.id)}
                        className={`flex items-center gap-2 px-3 py-2 cursor-pointer transition-colors ${
                          topic.id === selectedTopic 
                            ? 'bg-rose-50 dark:bg-rose-950/20 text-rose-700 dark:text-rose-300' 
                            : 'hover:bg-gray-50 dark:hover:bg-gray-700 text-gray-900 dark:text-gray-100'
                        }`}
                      >
                        <FolderOpen className="w-4 h-4 text-gray-500 flex-shrink-0" />
                        <span className="truncate">{topic.name}</span>
                        {topic.id === selectedTopic && (
                          <CheckCircle className="w-4 h-4 text-rose-500 ml-auto flex-shrink-0" />
                        )}
                      </div>
                    ))
                  ) : (
                    <div className="text-sm text-gray-500 px-3 py-4 text-center">
                      {debouncedSearchTerm ? (
                        <>
                          未找到匹配 "{debouncedSearchTerm}" 的项目
                          <button 
                            onClick={clearSearch}
                            className="block mx-auto mt-2 text-rose-500 hover:text-rose-600 text-xs underline"
                          >
                            清空搜索
                          </button>
                        </>
                      ) : (
                        '无可用项目'
                      )}
                    </div>
                  )}
                </div>
              </div>
            )}
          </div>
          <div className="text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap">
            共 {topics.length} 个项目
          </div>
        </div>

        {/* 进度看板 */}
        {loading ? (
          <div className="flex justify-center items-center h-64">
            <div className="flex items-center gap-3">
              <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-rose-600"></div>
              <span className="text-gray-600 dark:text-gray-400">加载中...</span>
            </div>
          </div>
        ) : (
          <DragDropContext onDragEnd={handleDragEnd}>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
              {Object.entries(statusConfig).map(([statusValue, config]) => {
                const Icon = config.icon
                const statusCopies = copies.filter(copy => copy.status === statusValue)
                
                return (
                  <Droppable key={statusValue} droppableId={statusValue}>
                    {(provided: DroppableProvided, snapshot: DroppableStateSnapshot) => (
                      <div
                        {...provided.droppableProps}
                        ref={provided.innerRef}
                        className={`${config.bgColor} ${config.borderColor} border-2 rounded-xl p-4 transition-all duration-200 ${
                          snapshot.isDraggingOver ? 'ring-2 ring-rose-400 scale-105' : ''
                        }`}
                      >
                        {/* 状态标题 */}
                        <div className="flex items-center justify-between mb-4">
                          <div className="flex items-center gap-2">
                            <div className={`${config.color} p-2 rounded-lg`}>
                              <Icon className="w-4 h-4 text-white" />
                            </div>
                            <h3 className={`font-semibold ${config.textColor}`}>
                              {statusValue}
                            </h3>
                          </div>
                          <div className={`${config.color} text-white text-xs px-2 py-1 rounded-full font-medium`}>
                            {statusCopies.length}
                          </div>
                        </div>
                        
                        {/* 文案列表 */}
                        <div className="space-y-3 min-h-[200px]">
                          {statusCopies.map((copy, index) => (
                            <Draggable key={copy.id} draggableId={copy.id} index={index}>
                              {(provided, snapshot) => (
                                <div
                                  ref={provided.innerRef}
                                  {...provided.draggableProps}
                                  className={`bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-4 shadow-sm hover:shadow-md transition-all duration-200 group ${
                                    snapshot.isDragging ? 'rotate-3 shadow-lg' : ''
                                  }`}
                                >
                                  <div className="flex items-start justify-between">
                                    <div className="flex-1 min-w-0">
                                      <h4 
                                        className="font-medium text-gray-900 dark:text-gray-100 hover:text-rose-600 dark:hover:text-rose-400 cursor-pointer transition-colors duration-200 truncate"
                                        onClick={() => {
                                          if (copy.status === '文案编辑中') {
                                            window.open(`/copy/${copy.id}`, '_blank')
                                          } else if (copy.status === '脚本制作中') {
                                            window.open(`/scripts/${copy.id}`, '_blank')
                                          } else if (copy.status === '拍摄中') {
                                            window.open(`/scripts/${copy.id}`, '_blank')
                                          }
                                        }}
                                      >
                                        {copy.title}
                                      </h4>
                                      <div className="flex items-center gap-2 mt-2">
                                        <Clock className="w-3 h-3 text-gray-400" />
                                        <p className="text-xs text-gray-500 dark:text-gray-400">
                                          进度: {copy.finished_script_num}/{copy.script_num}
                                        </p>
                                      </div>
                                      
                                      {/* 进度条 */}
                                      <div className="mt-2">
                                        <div className="w-full bg-gray-200 dark:bg-gray-700 rounded-full h-1.5">
                                          <div 
                                            className={`${config.color} h-1.5 rounded-full transition-all duration-300`}
                                            style={{
                                              width: `${(copy.script_num ?? 0) > 0 ? ((copy.finished_script_num ?? 0) / (copy.script_num ?? 1)) * 100 : 0}%`
                                            }}
                                          ></div>
                                        </div>
                                      </div>
                                    </div>
                                    
                                    {/* 拖拽手柄 */}
                                    <div 
                                      {...provided.dragHandleProps}
                                      className="ml-2 p-1 opacity-0 group-hover:opacity-100 transition-opacity duration-200 cursor-grab active:cursor-grabbing"
                                    >
                                      <GripVertical className="w-4 h-4 text-gray-400" />
                                    </div>
                                  </div>
                                </div>
                              )}
                            </Draggable>
                          ))}
                          {provided.placeholder}
                          
                          {/* 空状态 */}
                          {statusCopies.length === 0 && (
                            <div className="text-center py-8">
                              <div className="text-gray-400 dark:text-gray-500 text-sm">
                                暂无{statusValue}的文案
                              </div>
                            </div>
                          )}
                        </div>
                      </div>
                    )}
                  </Droppable>
                )
              })}
            </div>
          </DragDropContext>
        )}
      </div>
    </div>
  )
}
